package com.power.sifa.approve.controller;

import cn.dev33.satoken.annotation.SaCheckPermission;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.ObjectUtil;
import com.plf.common.domain.PageDataResponse;
import com.plf.common.domain.ResponseDTO;
import com.plf.common.file.model.FileVo;
import com.plf.common.utils.ExcelUtil;
import com.plf.common.utils.SpringHolder;
import com.plf.common.utils.StringUtil;
import com.plf.core.base.model.Ha_attachment;
import com.plf.core.common.file.FileController;
import com.power.sifa.approve.api.IAprv_process_materialsFeign;
import com.power.sifa.approve.model.*;
import com.power.sifa.approve.model.enumeration.Tp_procmaterialEnum;
import com.power.sifa.approve.model.enumeration.Tp_proctype;
import com.power.sifa.approve.model.enumeration.Tp_proctypeEnum;
import com.power.sifa.approve.model.pageInfo.Aprv_process_materialsPageInfo;
import com.power.sifa.approve.model.pojo.vo.CustomerNoArchiveVO;
import com.power.sifa.approve.model.pojo.vo.MaterialTreeVO;
import com.power.sifa.approve.service.*;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.domain.Page;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.Assert;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.*;
import java.util.stream.Collectors;



/**
 *   审批过程材料控制器
 */

@Slf4j
//@PowerLog
@RestController
@Api(value = "Aprv_process_materialsController",tags={"审批过程材料"})
public class Aprv_process_materialsController implements IAprv_process_materialsFeign{

    @Resource
    private Aprv_process_materialsService aprv_process_materialsService;

    @Resource
    private Apl_mainService apl_mainService;

    @Resource
    private Apl_dossierService apl_dossierService;

    @Resource
    private Aprv_materials_optionsService aprv_materials_optionsService;


    @Resource
    private Apl_matter_attachService apl_matter_attachService;

    @Resource
    private Apl_applicantService apl_applicantService;

    @Resource
    private Apl_agentService apl_agentService;

    @Resource
    private  Apl_thirdperService apl_thirdperService;


    @Override
    @ApiOperation("查询审批过程材料分页列表")
    @SaCheckPermission("aprv_process_materials_list")
    public ResponseDTO list(Aprv_process_materialsPageInfo pageInfo) {
        Assert.notNull(pageInfo, "pageInfo参数不能为空");
        Page<Aprv_process_materials> page = this.aprv_process_materialsService.findAll(pageInfo);
        List list = new ArrayList();
        if (!page.isEmpty()) {
            for (Aprv_process_materials aprv_process_materials : page) {
                aprv_process_materials.geneText();
                list.add(aprv_process_materials);
            }
        }
        PageDataResponse p = new PageDataResponse(list, page.getTotalElements(), page.getSize(), pageInfo.getPageNumber()<=1 ? 1 : pageInfo.getPageNumber());
        return ResponseDTO.succData(p);
    }

    @Override
    @ApiOperation("查看审批过程材料")
    @SaCheckPermission("aprv_process_materials_view")
    public ResponseDTO view(String id) {
        Assert.notNull(id, "id不能为空");
        Aprv_process_materials aprv_process_materials  = aprv_process_materialsService.getById(id);
        if (aprv_process_materials != null) {
            aprv_process_materials.geneText();
        }
        return ResponseDTO.succData(aprv_process_materials);
    }

    @Override
    @ApiOperation("删除审批过程材料")
    @SaCheckPermission("aprv_process_materials_del")
    public ResponseDTO delete(String id) {
        Assert.notNull(id, "id不能为空");
        aprv_process_materialsService.removeById(id);
        return ResponseDTO.succ();
    }

    @Override
    @ApiOperation("保存或修改审批过程材料")
    @SaCheckPermission("aprv_process_materials_save")
    public ResponseDTO save(Aprv_process_materials aprv_process_materials) {
        Assert.notNull(aprv_process_materials, "aprv_process_materials不能为空");
        aprv_process_materialsService.saveOrUpdate(aprv_process_materials);
        return ResponseDTO.succ();
    }

    @Override
    @ApiOperation(value="批量删除审批过程材料")
    @SaCheckPermission("aprv_process_materials_del")
    public ResponseDTO batchDel(String ids) {
        Assert.isTrue(StringUtils.hasText(ids), "ids不能为空");
        List<Integer> list = Arrays.asList(ids.split(",")).stream().map(s -> Integer.parseInt(s.trim())).collect(Collectors.toList());
        aprv_process_materialsService.removeByIds(list);
        return ResponseDTO.succ();
    }

    @Override
    @ApiOperation(value="导出excel")
    @SaCheckPermission("aprv_process_materials_list")
    public void output(HttpServletResponse response, Aprv_process_materialsPageInfo pageInfo) {
        Assert.notNull(pageInfo, "pageInfo不能为空");
        String title = "审批过程材料";
        String[] heads = {"applyid+nanoid","附件id","类型","创建人id","创建人","创建时间","引用主表id"};
        String[] fields = {"id","attachid","type","createuserid","createuser","createtime","applyid"};
        Page<Aprv_process_materials> page = this.aprv_process_materialsService.findAll(pageInfo);
        ExcelUtil.exportXls(title, heads, fields, page.getContent(), response);
    }

    @Override
    @ApiOperation(value="导出excel模板")
    public void exportExcelTemplate(HttpServletResponse response) {
        String title = "审批过程材料";
        //id自增或list从表可自行删除，需与导入项一致
        String[] heads = {"applyid+nanoid","附件id","类型","创建人id","创建人","创建时间","引用主表id"};
        ExcelUtil.exportXls(title, heads, null, null, response);
    }

	@Override
	@ApiOperation(value="导入excel")
	public ResponseDTO importExcel(MultipartFile file) throws IOException {
        Assert.notNull(file, "file不能为空");
        //id自增或list从表可自行删除，需与下载的模板中导入项一致
        String[] fields = {"id","attachid","type","createuserid","createuser","createtime","applyid"};
        List<Aprv_process_materials> list = (List<Aprv_process_materials>)ExcelUtil.Import(fields, file, Aprv_process_materials.class);
        if(!CollectionUtils.isEmpty(list)) {
            this.aprv_process_materialsService.saveAll(list);
        }
        return ResponseDTO.succ();
	}

    /**
     * 保存审批过程材料类型文件 -只保存单个材料文件
     * @param applyId 对应的申请主数据的id
     * @param fileType 对应的材料的类型
     * @param file 保存的文件
     * @return
     */
    @Override
    @ApiOperation(value="保存对应的材料文件")
    public ResponseDTO saveMaterial(String applyId, Integer fileType, Integer busiType, String userId,
                                    String userName, MultipartFile file) {
        Assert.notNull(file, "file不能为空");
        Assert.notNull(applyId, "业务申请id不能为空");
        FileController fileController = SpringHolder.getBean(FileController.class);
        try {
            // 获取保存的数据，将其保存的对应的数据库里
            ResponseDTO<FileVo> result = fileController.minioUpload(file, null, null);
            if (ObjectUtil.isNotEmpty(result) && result.getCode() == ResponseDTO.succ().getCode()) {
                FileVo fileData = result.getData();
                if (ObjectUtil.isNotNull(fileData)) {
                    Tp_procmaterialEnum procmaterialEnum = Tp_procmaterialEnum.getById(fileType);
                    Aprv_process_materials materialResult = aprv_process_materialsService.saveMaterial(fileData.getId(),
                            applyId, busiType, userId, userName,procmaterialEnum);
                    return ResponseDTO.succData(materialResult);
                }
            }
        } catch (Exception e) {
            log.error("文件保存异常:{}", e.getMessage());
            return ResponseDTO.wrap(500, "文件保存异常");
        }
        return ResponseDTO.succ();
    }



    /**
     * 保存审批过程材料类型文件 -可保存多个材料文件
     * @param applyId 对应的申请主数据的id
     * @param fileType 对应的材料的类型
     * @param files 保存的文件
     * @return
     */
    @Override
    @ApiOperation(value="保存对应的材料文件")
    public ResponseDTO saveMaterialMulti(String applyId, Integer fileType, Integer busiType, String userId,
                                          String userName, List<MultipartFile> files) {
        Assert.notNull(files, "files不能为空");
        Assert.notNull(applyId, "业务申请id不能为空");
        try {
            // 获取保存的数据，将其保存的对应的数据库里
            FileController fileController = SpringHolder.getBean(FileController.class);
            List<Aprv_process_materials> saveResult = new ArrayList<>();
            if (CollectionUtil.isNotEmpty(files)) {
                ResponseDTO<List> result = fileController.minioUpload(files, null, null);
                if (ObjectUtil.isNotEmpty(result) && result.getCode() == ResponseDTO.succ().getCode()) {
                    List<FileVo> fileDataList = result.getData();
                    if (CollectionUtil.isNotEmpty(fileDataList)) {
                        Tp_procmaterialEnum procmaterialEnum = Tp_procmaterialEnum.getById(fileType);
                        fileDataList.stream().forEach(fileData -> {
                            Aprv_process_materials materialResult = aprv_process_materialsService.saveMaterial(fileData.getId(), applyId, busiType, userId, userName, procmaterialEnum);
                            saveResult.add(materialResult);
                        });
                        return ResponseDTO.succData(saveResult);
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            log.error("文件保存异常:{}", e.getMessage());
            return ResponseDTO.wrap(500, "文件保存异常");
        }
        return ResponseDTO.succ();
    }

    /**
     * 保存自定义的材料类型定义的文件
     * @param applyId 申请主表的applyid
     * @param fileType 材料类型
     * @param busiType 业务类型
     * @param userId
     * @param userName
     * @param replyCustomerId 自定义材料类型依赖的id
     * @param files
     * @return
     */
    @Override
    public ResponseDTO saveMaterialCustomer(String applyId, Integer fileType, Integer busiType, String userId,
                                            String userName, String replyCustomerId, List<MultipartFile> files) {
        Assert.notNull(files, "files不能为空");
        Assert.notNull(applyId, "业务申请id不能为空");
        try {
            // 获取保存的数据，将其保存的对应的数据库里
            FileController fileController = SpringHolder.getBean(FileController.class);
            List<Aprv_process_materials> saveResult = new ArrayList<>();
            ResponseDTO<List> result = fileController.minioUpload(files, null, null);
            if (ObjectUtil.isNotEmpty(result) && result.getCode() == ResponseDTO.succ().getCode()) {

                List<FileVo> fileDataList = result.getData();
                if (CollectionUtil.isNotEmpty(fileDataList)) {
                    fileDataList.stream().forEach(fileData -> {
                        Aprv_process_materials materialResult = aprv_process_materialsService.saveMaterialCustomer(fileData,
                                applyId, busiType, userId, userName, replyCustomerId);
                        saveResult.add(materialResult);
                    });
                    return ResponseDTO.succData(saveResult);
                }
            }
        } catch (Exception e) {
            log.error("文件保存异常:{}", e.getMessage());
            return ResponseDTO.wrap(500, "文件保存异常");
        }
        return ResponseDTO.succ();
    }

    /**
     * 送达阶段上传文件接口
     * @param applyid applyid
     * @param mattype  材料类型
     * @param userId 用户id
     * @param userName 用户名称
     * @param files 文件
     * @return
     */
    @Override
    public ResponseDTO saveMaterialArrive(String applyid, Integer mattype, String userId, String userName,
                                          List<MultipartFile> files) {
        Assert.notNull(files, "files不能为空");
        Assert.notNull(applyid, "applyid不能为空");
        try {
            // 获取保存的数据，将其保存的对应的数据库里
            FileController fileController = SpringHolder.getBean(FileController.class);
            List<Aprv_process_materials> saveResult = new ArrayList<>();
            ResponseDTO<List> result = fileController.minioUpload(files, null, null);
            if (ObjectUtil.isNotEmpty(result) && result.getCode() == ResponseDTO.succ().getCode()) {
                List<FileVo> fileDataList = result.getData();
                if (CollectionUtil.isNotEmpty(fileDataList)) {
                    fileDataList.stream().forEach(fileData -> {
                        Tp_procmaterialEnum procmaterialEnum = Tp_procmaterialEnum.getById(mattype);
                        Tp_proctypeEnum proctypeEnum = Tp_proctypeEnum.getByMaterilas(procmaterialEnum);
                        Aprv_process_materials materialResult = aprv_process_materialsService.saveMaterialRepeat(fileData,
                                applyid, ObjectUtil.isNotNull(proctypeEnum) ? proctypeEnum.getId() : null, userId, userName,procmaterialEnum);
                        saveResult.add(materialResult);
                    });
                }
                return ResponseDTO.succData(saveResult);
            }
        } catch (Exception e) {
            e.printStackTrace();
            log.error("文件保存异常:{}", e.getMessage());
            return ResponseDTO.wrap(500, "文件保存异常");
        }
        return ResponseDTO.succ();


    }

    /**
     * 删除审批过程材料类型文件
     * @param materialId 记录数据表主键id
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public ResponseDTO deleteMaterial(String materialId) {
        Assert.notNull(materialId, "材料文件数据库主键不能为空");
        try {
            Aprv_process_materials materials  = aprv_process_materialsService.getById(materialId);
            if (ObjectUtil.isNotNull(materials)) {
                String fileId = materials.getAttachid();
                // 获取保存的数据，将其保存的对应的数据库里
                FileController fileController = SpringHolder.getBean(FileController.class);
                ResponseDTO result = fileController.minioRemove(null, fileId);
                if (ObjectUtil.isNotEmpty(result) && result.getCode() == ResponseDTO.succ().getCode()) {
                    // 删除数据库关联的那条记录
                    aprv_process_materialsService.removeById(materialId);
                    aprv_materials_optionsService.deleteMaterialOptions(materialId);
                }
            }
        } catch (Exception e) {
            log.error("文件删除异常:{}", e.getMessage());
            return ResponseDTO.wrap(500, "文件删除异常");
        }
        return ResponseDTO.succ();
    }


    /**
     * 通过applID获取对应的材料文件
     */
    @Override
    public ResponseDTO getMaterialByApplyId(Aprv_process_materialsPageInfo pageInfo) {
        Assert.notNull(pageInfo.getF_applyid(), "applyid不能为空");
        List<Aprv_process_materials> materials = this.aprv_process_materialsService.queryMaterialByApplyId(pageInfo.getF_applyid());
        Map<String, List<Aprv_process_materials>> materialMap = new HashMap<>();
        if (CollectionUtil.isNotEmpty(materials)) {
            materialMap = materials.stream().filter(item -> ObjectUtil.isNotNull(item.getType())).collect(Collectors.groupingBy(material -> Tp_proctypeEnum.getById(material.getType()).getKey()));
        }
        return ResponseDTO.succData(materialMap);
    }

    /**
     * 通过applID获取对应的材料文件 包含材料文件和系统文书
     */
    @Override
    public ResponseDTO getAllMaterialByApplyId(String applyid) {
        Assert.notNull(applyid, "applyid不能为空");
        return ResponseDTO.succData(aprv_process_materialsService.getAllMaterialByApplyId(applyid));
    }

    @Override
    public ResponseDTO getMaterialList(Aprv_process_materialsPageInfo pageInfo) {
        return ResponseDTO.succData(this.aprv_process_materialsService.getMaterialList(pageInfo));
    }

    /**
     * 通过applyId 查询全部的系统文书文件
     * @param applyid
     * @return
     */
    @Override
    public ResponseDTO queryDocumentByApplyId(String applyid) {
        Assert.notNull(applyid, "applyid不能为空");
        List<Aprv_process_materials> documentList = this.aprv_process_materialsService.queryDocumentByApplyId(applyid);
        Map<String, List<Aprv_process_materials>> documentMap = new HashMap<>();
        if (CollectionUtil.isNotEmpty(documentList)) {
            documentMap = documentList.stream().filter(item -> ObjectUtil.isNotNull(item.getType())).collect(Collectors.groupingBy(material -> Tp_proctypeEnum.getById(material.getType()).getKey()));
        }
        return ResponseDTO.succData(documentMap);
    }

    /**
     * 通过applyid查询未归档的自定义文件
     * @param applyid
     * @return
     */
    @Override
    public ResponseDTO queryNoArchiveCustomerMaterial(String applyid) {
        Assert.notNull(applyid, "applyid不能为空");
        // 查询全部的材料
        List<Aprv_process_materials> filterMaterials = new ArrayList<>();
        // 查询过程材料
        List<Aprv_process_materials> allMaterials = aprv_process_materialsService.queryMaterialByApplyId(applyid);
        List<CustomerNoArchiveVO> result = new ArrayList<>();
        if (CollectionUtil.isNotEmpty(allMaterials)) {
            // 查询全部的已归档的数据
            List<Apl_dossier> aplDossierList = this.apl_dossierService.getDocTreeListByApplyid(applyid);
            if (CollectionUtil.isNotEmpty(aplDossierList)) {
                Set<String> materialSet = aplDossierList.stream().map((Apl_dossier::getMatid)).collect(Collectors.toSet());
                filterMaterials = allMaterials.stream().filter(element -> !StringUtil.isEmpty(element.getReply_attachid()) && !materialSet.contains(element.getAttachid())).collect(Collectors.toList());
            }
            // 分类
            if (CollectionUtil.isNotEmpty(filterMaterials)) {
                Map<String, List<Aprv_process_materials>> materialGroups = filterMaterials.stream().collect(Collectors.groupingBy(Aprv_process_materials::getReply_attachid));
                for(String key : materialGroups.keySet()) {
                    List<Aprv_process_materials> noArchiveMaterials = materialGroups.get(key);
                    if (CollectionUtil.isNotEmpty(noArchiveMaterials)) {
                        result.add(CustomerNoArchiveVO.builder().customer(noArchiveMaterials.get(0).getCustomerMaterial())
                        .materials(noArchiveMaterials).build());
                    }
                }
            }
        }
        // 拿取全部的自定义材料枚举项
        // 按照对应的分类
        return ResponseDTO.succData(result);
    }

    @Override
    public ResponseDTO regeneration() {
        try {
            this.aprv_process_materialsService.regeneration();
            return ResponseDTO.succ();
        } catch (Exception e) {
            e.printStackTrace();
            log.error("/aprv_process_materials/regeneration ->  msg[{}]", e.getMessage());
            return ResponseDTO.wrap(500, "根据新版模板重新生成文书失败");
        }
    }

    private List<MaterialTreeVO> buildMaterialTree () {
        List<MaterialTreeVO> materialTree = new ArrayList<>();
        // 第一层级节点设置
        MaterialTreeVO root1 = MaterialTreeVO.builder().key("1").title("申请材料").level(1).disabled(Boolean.TRUE).build();
        MaterialTreeVO root2 = MaterialTreeVO.builder().key("2").title("人员材料").level(1).disabled(Boolean.TRUE).build();
        MaterialTreeVO root3 = MaterialTreeVO.builder().key("3").title("办案程序").level(1).disabled(Boolean.TRUE).build();

        // 第三层级节点设置
        MaterialTreeVO root3_1 = MaterialTreeVO.builder().key("31").parentKey("3").disabled(Boolean.TRUE).title("受理").level(2).build();
        // 受理节点设置
        MaterialTreeVO root3_1_1 = MaterialTreeVO.builder().key(String.valueOf(Tp_proctype.MATER_MEDIATE)).parentKey("31").disabled(Boolean.TRUE).title("受理前调解").level(3).build();
        MaterialTreeVO root3_1_2 = MaterialTreeVO.builder().key(String.valueOf(Tp_proctype.ACCEPT_RESULT)).parentKey("31").disabled(Boolean.TRUE).title("撤回").level(3).build();
        MaterialTreeVO root3_1_3 = MaterialTreeVO.builder().key(String.valueOf(Tp_proctype.ACCEPT_APPEND)).parentKey("31").disabled(Boolean.TRUE).title("补正").level(3).build();
        MaterialTreeVO root3_1_4 = MaterialTreeVO.builder().key(String.valueOf(Tp_proctype.ACCEPT_ACCEPT)).parentKey("31").disabled(Boolean.TRUE).title("受理").level(3).build();
        MaterialTreeVO root3_1_5 = MaterialTreeVO.builder().key(String.valueOf(Tp_proctype.ACCEPT_NOACCEPT)).parentKey("31").disabled(Boolean.TRUE).title("不予受理").level(3).build();

        MaterialTreeVO root3_2 = MaterialTreeVO.builder().key("32").parentKey("3").disabled(Boolean.TRUE).title("审理").level(2).build();
        MaterialTreeVO root3_2_1 = MaterialTreeVO.builder().key(String.valueOf(Tp_proctype.HEAR_MEDIATE)).parentKey("32").disabled(Boolean.TRUE).title("受理后调解").level(3).build();
        MaterialTreeVO root3_2_2 = MaterialTreeVO.builder().key(String.valueOf(Tp_proctype.HEAR_TRAWL)).parentKey("32").disabled(Boolean.TRUE).title("查阅复制").level(3).build();
        MaterialTreeVO root3_2_3 = MaterialTreeVO.builder().key(String.valueOf(Tp_proctype.HEAR_TRANSFORM)).parentKey("32").disabled(Boolean.TRUE).title("程序转换").level(3).build();
        MaterialTreeVO root3_2_4 = MaterialTreeVO.builder().key(String.valueOf(Tp_proctype.HEAR_MOBILIZE)).parentKey("32").disabled(Boolean.TRUE).title("调卷").level(3).build();
        MaterialTreeVO root3_2_5 = MaterialTreeVO.builder().key(String.valueOf(Tp_proctype.HEAR_ADVICE)).parentKey("32").disabled(Boolean.TRUE).title("听取意见").level(3).build();
        MaterialTreeVO root3_2_6 = MaterialTreeVO.builder().key(String.valueOf(Tp_proctype.HEAR_SURVEY)).parentKey("32").disabled(Boolean.TRUE).title("调查").level(3).build();
        MaterialTreeVO root3_2_7 = MaterialTreeVO.builder().key(String.valueOf(Tp_proctype.HEAR_IDENTIFY)).parentKey("32").disabled(Boolean.TRUE).title("鉴定").level(3).build();
        MaterialTreeVO root3_2_8 = MaterialTreeVO.builder().key(String.valueOf(Tp_proctype.HEAR_EXPERT)).parentKey("32").disabled(Boolean.TRUE).title("专家论证").level(3).build();
        MaterialTreeVO root3_2_9 = MaterialTreeVO.builder().key(String.valueOf(Tp_proctype.HEAR_INQUEST)).parentKey("32").disabled(Boolean.TRUE).title("勘验").level(3).build();
        MaterialTreeVO root3_2_10 = MaterialTreeVO.builder().key(String.valueOf(Tp_proctype.HEAR_HEARING)).parentKey("32").disabled(Boolean.TRUE).title("听证").level(3).build();
        MaterialTreeVO root3_2_11 = MaterialTreeVO.builder().key(String.valueOf(Tp_proctype.HEAR_STOP)).parentKey("32").disabled(Boolean.TRUE).title("停止执行").level(3).build();
        MaterialTreeVO root3_2_12 = MaterialTreeVO.builder().key(String.valueOf(Tp_proctype.HEAR_DELAY)).parentKey("32").disabled(Boolean.TRUE).title("延期").level(3).build();
        MaterialTreeVO root3_2_13 = MaterialTreeVO.builder().key(String.valueOf(Tp_proctype.HEAR_REST)).parentKey("32").disabled(Boolean.TRUE).title("中止").level(3).build();
        MaterialTreeVO root3_2_14 = MaterialTreeVO.builder().key(String.valueOf(Tp_proctype.HEAR_DECISION)).parentKey("32").disabled(Boolean.TRUE).title("决定").level(3).build();

        MaterialTreeVO root3_3 = MaterialTreeVO.builder().key("33").parentKey("3").disabled(Boolean.TRUE).title("执行").level(2).build();
        MaterialTreeVO root3_3_1 = MaterialTreeVO.builder().key(String.valueOf(Tp_proctype.EXECUTE_SELF)).parentKey("33").disabled(Boolean.TRUE).title("自行履行").level(3).build();
        MaterialTreeVO root3_3_2 = MaterialTreeVO.builder().key(String.valueOf(Tp_proctype.EXECUTE_PERFORM)).parentKey("33").disabled(Boolean.TRUE).title("责令履行").level(3).build();
        MaterialTreeVO root3_3_3 = MaterialTreeVO.builder().key(String.valueOf(Tp_proctype.EXECUTE_FORCE_UNIT)).parentKey("33").disabled(Boolean.TRUE).title("复议机关强制执行").level(3).build();
        MaterialTreeVO root3_3_4 = MaterialTreeVO.builder().key(String.valueOf(Tp_proctype.EXECUTE_FORCE_LAW)).parentKey("33").disabled(Boolean.TRUE).title("委托人民法院强制执行").level(3).build();

        root3_1.setChildren(Arrays.asList(root3_1_1,root3_1_2,root3_1_3,root3_1_4,root3_1_5));
        root3_2.setChildren(Arrays.asList(root3_2_1,root3_2_2,root3_2_3,root3_2_4,root3_2_5,root3_2_6,root3_2_7,root3_2_8,root3_2_9,
                root3_2_10,root3_2_11,root3_2_12,root3_2_13,root3_2_14));
        root3_3.setChildren(Arrays.asList(root3_3_1,root3_3_2,root3_3_3,root3_3_4));

        root3.setChildren(Arrays.asList(root3_1,root3_2,root3_3));
        materialTree.add(root1);
        materialTree.add(root2);
        materialTree.add(root3);
        return materialTree;

    }


    @Override
    public ResponseDTO screenMaterials(String applyid) {
        List<MaterialTreeVO> materialTreeVOList = buildMaterialTree();
        // 查询申请材料
        // 行政复议申请书记附件材料及申请人提供的证据清单及证据材料
        List<Apl_matter_attach> matterMaterials = apl_matter_attachService.queryListAndFileByApplyid(applyid);
        if (CollectionUtil.isNotEmpty(matterMaterials)) {
            MaterialTreeVO root1 = materialTreeVOList.get(0);
            List<MaterialTreeVO> root1_children = new ArrayList<>();
            matterMaterials.stream().forEach(matter -> {
               MaterialTreeVO node = MaterialTreeVO.builder().key(matter.getId()).parentKey(root1.getKey()).disabled(Boolean.TRUE).title(matter.getName()).level(2).build();
               if (CollectionUtil.isNotEmpty(matter.getFileList())) {
                   List<MaterialTreeVO> material_children = new ArrayList<>();
                   matter.getFileList().stream().forEach(file -> {
                       MaterialTreeVO material = MaterialTreeVO.builder().key(file.get("attachmentid").toString()).parentKey(node.getKey()).disabled(Boolean.FALSE)
                               .title(file.get("name").toString()).fileName(file.get("name").toString())
                               .fileUrl(file.get("url").toString()).level(3).build();
                       material_children.add(material);
                   });
                   node.setChildren(material_children);
               }
                root1_children.add(node);
            });
            root1.setChildren(root1_children);
        }
        // 查询人员材料
        // 查询申请人及委托代理人
        Map<Integer, List<Apl_applicant>> applicantMaps = apl_applicantService.getApplicantWithGroup(applyid);
        if (ObjectUtil.isNotEmpty(applicantMaps)) {
            for (Integer key: applicantMaps.keySet()) {
                List<Apl_applicant> applicantLists = applicantMaps.get(key);
                if (CollectionUtil.isNotEmpty(applicantLists)) {
                    MaterialTreeVO root2 = materialTreeVOList.get(1);
                    MaterialTreeVO root2_child = MaterialTreeVO.builder().key("21").parentKey(root2.getKey()).disabled(Boolean.TRUE).title("申请人").level(2).build();
                    List<MaterialTreeVO> root2_materials = new ArrayList<>();
                    applicantLists.stream().forEach(applicant -> {
                        if(CollectionUtil.isNotEmpty(applicant.getFilecardList())) {
                            applicant.getFilecardList().stream().forEach(filecard -> {
                                MaterialTreeVO material = MaterialTreeVO.builder().key(filecard.getId()).parentKey(root2_child.getKey()).disabled(Boolean.FALSE)
                                        .title(filecard.getFilename()).fileName(filecard.getFilename())
                                        .fileUrl(filecard.getPath()).level(3).build();
                                root2_materials.add(material);
                            });
                        }
                        if (CollectionUtil.isNotEmpty(applicant.getDoccardList())) {
                            applicant.getDoccardList().stream().forEach(filecard -> {
                                MaterialTreeVO material = MaterialTreeVO.builder().key(filecard.getId()).parentKey(root2_child.getKey()).disabled(Boolean.FALSE)
                                        .title(filecard.getFilename()).fileName(filecard.getFilename())
                                        .fileUrl(filecard.getPath()).level(3).build();
                                root2_materials.add(material);
                            });
                        }
                    });
                    root2_child.setChildren(root2_materials);
                    List<MaterialTreeVO> childList = root2.getChildren();
                    if (CollectionUtil.isNotEmpty(childList)) {
                        childList.add(root2_child);
                    } else {
                        childList = new ArrayList<>();
                        childList.add(root2_child);
                        root2.setChildren(childList);
                    }
                }
            }
        }
        // 查询代理人
        Map<Integer, List<Apl_agent>> agentMaps = apl_agentService.getAgentWithGroup(applyid);
        if (ObjectUtil.isNotEmpty(agentMaps)) {
            for (Integer key: agentMaps.keySet()) {
                List<Apl_agent> agentLists = agentMaps.get(key);
                if (CollectionUtil.isNotEmpty(agentLists)) {
                    MaterialTreeVO root2 = materialTreeVOList.get(1);
                    MaterialTreeVO root2_child = MaterialTreeVO.builder().key("22").parentKey(root2.getKey()).disabled(Boolean.TRUE).title("代理人").level(2).build();
                    List<MaterialTreeVO> root2_materials = new ArrayList<>();
                    agentLists.stream().forEach(agent -> {
                        if(CollectionUtil.isNotEmpty(agent.getFilecardList())) {
                            agent.getFilecardList().stream().forEach(filecard -> {
                                MaterialTreeVO material = MaterialTreeVO.builder().key(filecard.getId()).parentKey(root2_child.getKey()).disabled(Boolean.FALSE)
                                        .title(filecard.getFilename()).fileName(filecard.getFilename())
                                        .fileUrl(filecard.getPath()).level(3).build();
                                root2_materials.add(material);
                            });
                        }
                        if (CollectionUtil.isNotEmpty(agent.getDoccardList())) {
                            agent.getDoccardList().stream().forEach(filecard -> {
                                MaterialTreeVO material = MaterialTreeVO.builder().key(filecard.getId()).parentKey(root2_child.getKey()).disabled(Boolean.FALSE)
                                        .title(filecard.getFilename()).fileName(filecard.getFilename())
                                        .fileUrl(filecard.getPath()).level(3).build();
                                root2_materials.add(material);
                            });
                        }
                    });
                    root2_child.setChildren(root2_materials);
                    List<MaterialTreeVO> childList = root2.getChildren();
                    if (CollectionUtil.isNotEmpty(childList)) {
                        childList.add(root2_child);
                    } else {
                        childList = new ArrayList<>();
                        childList.add(root2_child);
                        root2.setChildren(childList);
                    }
                }
            }
        }


        // 查询第三人
        Map<Integer, List<Apl_thirdper>> thirdMap = apl_thirdperService.getThirdWithGroup(applyid);
        if (ObjectUtil.isNotEmpty(thirdMap)) {
            for (Integer key: thirdMap.keySet()) {
                List<Apl_thirdper> thirdperList = thirdMap.get(key);
                if (CollectionUtil.isNotEmpty(thirdperList)) {
                    MaterialTreeVO root2 = materialTreeVOList.get(1);
                    MaterialTreeVO root2_child = MaterialTreeVO.builder().key("23").parentKey(root2.getKey()).disabled(Boolean.TRUE).title("第三人").level(2).build();
                    List<MaterialTreeVO> root2_materials = new ArrayList<>();
                    thirdperList.stream().forEach(thirdper -> {
                        if(CollectionUtil.isNotEmpty(thirdper.getFilecardList())) {
                            thirdper.getFilecardList().stream().forEach(filecard -> {
                                MaterialTreeVO material = MaterialTreeVO.builder().key(filecard.getId()).parentKey(root2_child.getKey()).disabled(Boolean.FALSE)
                                        .title(filecard.getFilename()).fileName(filecard.getFilename())
                                        .fileUrl(filecard.getPath()).level(3).build();
                                root2_materials.add(material);
                            });
                        }
                        if (CollectionUtil.isNotEmpty(thirdper.getDoccardList())) {
                            thirdper.getDoccardList().stream().forEach(filecard -> {
                                MaterialTreeVO material = MaterialTreeVO.builder().key(filecard.getId()).parentKey(root2_child.getKey()).disabled(Boolean.FALSE)
                                        .title(filecard.getFilename()).fileName(filecard.getFilename())
                                        .fileUrl(filecard.getPath()).level(3).build();
                                root2_materials.add(material);
                            });
                        }
                        if (CollectionUtil.isNotEmpty(thirdper.getThirdEvidenceList())) {
                            thirdper.getThirdEvidenceList().stream().forEach(filecard -> {
                                MaterialTreeVO material = MaterialTreeVO.builder().key(filecard.getId()).parentKey(root2_child.getKey()).disabled(Boolean.FALSE)
                                        .title(filecard.getFilename()).fileName(filecard.getFilename())
                                        .fileUrl(filecard.getPath()).level(3).build();
                                root2_materials.add(material);
                            });
                        }
                    });
                    root2_child.setChildren(root2_materials);
                    List<MaterialTreeVO> childList = root2.getChildren();
                    if (CollectionUtil.isNotEmpty(childList)) {
                        childList.add(root2_child);
                    } else {
                        childList = new ArrayList<>();
                        childList.add(root2_child);
                        root2.setChildren(childList);
                    }
                }
            }
        }

        List<Aprv_process_materials> materials = aprv_process_materialsService.queryAttachByApplyId(applyid);
        // 查询被申请人答复通知书
        List<Aprv_process_materials> targetReplyMaterials = materials.stream().filter(matter -> matter.getType().equals(Tp_proctype.HEAR_REPLY)).collect(Collectors.toList());
       // 生成被申请人答复通知的节点
        if (CollectionUtil.isNotEmpty(targetReplyMaterials)) {
            MaterialTreeVO root2 = materialTreeVOList.get(1);
            MaterialTreeVO root2_child = MaterialTreeVO.builder().key("24").parentKey(root2.getKey()).disabled(Boolean.TRUE).title("被申请人").level(2).build();
            List<MaterialTreeVO> root2_materials = new ArrayList<>();
            targetReplyMaterials.stream().forEach(targetFile -> {
                if (ObjectUtil.isNotEmpty(targetFile.getFile())) {
                    MaterialTreeVO material = MaterialTreeVO.builder().key(targetFile.getId()).parentKey(root2_child.getKey()).disabled(Boolean.FALSE)
                            .title(targetFile.getFile().getFilename()).fileName(targetFile.getFile().getFilename())
                            .fileUrl(targetFile.getFile().getPath()).level(3).build();
                    root2_materials.add(material);

                }
            });
            root2_child.setChildren(root2_materials);
            List<MaterialTreeVO> childList = root2.getChildren();
            if (CollectionUtil.isNotEmpty(childList)) {
                childList.add(root2_child);
            } else {
                childList = new ArrayList<>();
                childList.add(root2_child);
                root2.setChildren(childList);
            }
        }

        // 受理阶段
        List<Integer> acceptProperties = Arrays.asList(Tp_proctype.MATER_MEDIATE,Tp_proctype.ACCEPT_RESULT,
                Tp_proctype.ACCEPT_APPEND,  Tp_proctype.ACCEPT_ACCEPT,Tp_proctype.ACCEPT_NOACCEPT);
        // 执行阶段
        List<Integer> executeProperties = Arrays.asList(Tp_proctype.EXECUTE_SELF,Tp_proctype.EXECUTE_PERFORM,
                Tp_proctype.EXECUTE_FORCE_UNIT,  Tp_proctype.EXECUTE_FORCE_LAW);
        MaterialTreeVO root3 = materialTreeVOList.get(2);
        if (CollectionUtil.isNotEmpty(materials)) {
            List<MaterialTreeVO> root_children = root3.getChildren();
            MaterialTreeVO acceptNode = root_children.get(0);
            MaterialTreeVO hearNode = root_children.get(1);
            MaterialTreeVO executeNode = root_children.get(2);
            materials.stream().forEach(matter -> {
                // 受理阶段
                List<MaterialTreeVO> child_protype;
                if (acceptProperties.contains(matter.getType())) {
                    child_protype = acceptNode.getChildren();
                } else if (executeProperties.contains(matter.getType())) {
                    // 执行阶段
                    child_protype = executeNode.getChildren();
                } else {
                    // 审理阶段
                    child_protype = hearNode.getChildren();
                }
                if (ObjectUtil.isNotEmpty(matter.getFile())) {
                    MaterialTreeVO findNode = child_protype.stream().filter(child -> child.getKey().equals(matter.getType().toString())).findAny().orElse(null);
                    if (ObjectUtil.isNotEmpty(findNode)) {
                        List<MaterialTreeVO> newNodeList = CollectionUtil.isNotEmpty(findNode.getChildren()) ? findNode.getChildren() : new ArrayList();
                        Ha_attachment attachment = matter.getFile();
                        MaterialTreeVO material = MaterialTreeVO.builder().key(attachment.getId()).parentKey(findNode.getKey()).disabled(Boolean.FALSE)
                                .title(attachment.getFilename()).fileName(attachment.getFilename())
                                .fileUrl(attachment.getPath()).level(3).build();
                        newNodeList.add(material);
                        findNode.setChildren(newNodeList);
                    }
                }
            });
        }

        return ResponseDTO.succData(materialTreeVOList);
    }


}
